package test.concurrent;

import java.util.concurrent.locks.StampedLock;

/**
 * @author yachao.guo
 * @date 2019-06-27 17:01
 */
public class Point {

    private int x, y;
    final StampedLock sl = new StampedLock();

    double distanceFromOrigin() {
        //乐观读
        long stamp = sl.tryOptimisticRead();
        int cutX = x;
        int cutY = y;
        //如果在乐观读期间是否存在写操作
        if (!sl.validate(stamp)) {
            //升级为悲观读锁
            stamp = sl.readLock();
            try {
                cutX = x;
                cutY = y;
            } finally {
                sl.unlockRead(stamp);
            }
        }
        return Math.sqrt(cutX * cutX + cutY * cutY);

    }
}
